package org.tobaccomain.configuration;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.tobaccomain.pojo.entity.Result;
import org.tobaccomain.utils.JwtUtils;


@Slf4j
@Component
public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求的url
        String url = request.getRequestURI();
        //判断是不是登录请求
        if(url.contains("login") || url.contains("forget")){
            //登录请求，直接放行
            return true;
        }
        //获取jwt令牌
        String jwt = request.getHeader("Authorization");
        //判断jwt令牌是否存在
        if(!StringUtils.hasLength(jwt)){
            //尝试获取请求参数中的token
            jwt = request.getParameter("Authorization");
            if(!StringUtils.hasLength(jwt)){
                //jwt不存在，返回错误信息
                Result result = Result.error("NOT_LOGIN");
                //将错误结果返回给前端
                String error = JSONObject.toJSONString(result);
                response.getWriter().write(error);
                return false;
            }
        }
        //jwt令牌存在，开始解析
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            //解析错误，返回为登录信息
            Result result = Result.error("NOT_LOGIN");
            //将错误结果返回给前端
            String error = JSONObject.toJSONString(result);
            response.getWriter().write(error);
            return false;
        }

        //登录验证成功，放行
        return true;

    }
}
